<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <!-- 进度条 -->
      <el-progress v-if="showProgress" :percentage="percent" />
    </el-upload>
  </div>
</template>

<script>
// 固定写法
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id(秘钥)
const cos = new COS({
  SecretId: 'AKIDnSt65pKaaMxKTN5aqwnTv86qLbbLo1zi',
  SecretKey: 'Xpqb9TWLuEDwPcZG8l8FsFPJxKRVVRDm'
})
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      showProgress: false,
      imageUrl: '',
      percent: 0 // 上传进度
    }
  },
  methods: {
    upload(res) {
      console.log(res, 'res')
      //   将文件上传到腾讯云
      if (res.file) {
        this.showProgress = true // 进度打开
      }
      cos.putObject({
        Bucket: 'wh81-1257017897', /* 存储桶 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: res.file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: res.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log('上传文件进度.....', JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        // 无论上传成功还是失败，都会执行该回调函数，如果成功，那么就打印data，如果失败，就打印err
        console.log(err || data)
        this.showProgress = false
        // 上传成功之后
        if (data.statusCode === 200) {
          this.$emit('input', `https:${data.Location}`)
          console.log(' this.imageUrl ', this.imageUrl)
        }
      })
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
